package io.github.bigbird0101.yousishi.sql.print;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.LoaderClassPath;

/**
 * @author m15179835326@163.com
 * @date 2023-04-06 10:51
 */
public class H2Adapter extends AbstractPrintSql{
    public static final String CLASS_NAME="org/h2/jdbc/JdbcPreparedStatement";
    @Override
    public boolean match(String className) {
        return CLASS_NAME.equals(className);
    }

    @Override
    public byte[] doPrintSqlClass(ClassLoader classLoader,Boolean isFormatSql) {
        try {
            ClassPool classPool = ClassPool.getDefault();
            classPool.appendClassPath(new LoaderClassPath(classLoader));
            String classname = CLASS_NAME.replaceAll("/", ".");
            CtClass ctClass = classPool.get(classname);
            ctClass.addMethod(getPrintSqlMethod(ctClass));
            CtMethod m1 = ctClass.getDeclaredMethod("execute", new CtClass[]{});
            m1.insertBefore("{davaPrintSql(sqlStatement," + isFormatSql + ");}");
            CtMethod m2 = ctClass.getDeclaredMethod("executeQuery", new CtClass[]{});
            m2.insertBefore("{davaPrintSql(sqlStatement," + isFormatSql + ");}");
            CtMethod m3 = ctClass.getDeclaredMethod("executeUpdate", new CtClass[]{});
            m3.insertBefore("{davaPrintSql(sqlStatement," + isFormatSql + ");}");
            return ctClass.toBytecode();
        }catch (Exception exception){
            throw new RuntimeException(exception);
        }
    }
}
